import { defineStore } from 'pinia'
import {
  delUser,
  getToken,
  getUser,
  removeToken,
  setToken,
  setUser,
  updateUser
} from '@/utils/auth'
import { getUserInfoByToken } from '@/api/user'

export const useUserStore = defineStore({
  id: 'user',
  state: () => ({
    token: getToken(),
    userInfo: getUser(),
    loading: false
  }),
  getters: {
    isLoggedIn() {
      return !!this.token && !!this.userInfo
    }
  },
  actions: {
    setLoading(loading) {
      this.loading = loading
    },
    async login(token) {
      this.token = token
      setToken(token)
      try {
        const res = await getUserInfoByToken(token)
        this.userInfo = res.data
        setUser(JSON.stringify(res.data))
        localStorage.removeItem('uid')
        return this.userInfo // 返回 Promise 对象的结果
      } catch (error) {
        throw error
      }
    },
    async updateUser(updatedInfo) {
      try {
        this.userInfo = updatedInfo
        updateUser(JSON.stringify(updatedInfo))
      } catch (error) {
        throw error
      }
    },
    async refreshUserInfo() {
      try {
        const res = await getUserInfoByToken(this.token)
        this.userInfo = res.data
        setUser(JSON.stringify(res.data))
      } catch (error) {
        throw error
      }
    },
    logOut() {
      this.userInfo = null
      this.token = null
      delUser()
      removeToken()
    }
  }
})
